
import { login } from '@/services/user'
import { Module } from 'vuex'
import { Session } from '@/utils/storage'
import { UserState, RootStateTypes } from '@/store/interface/index'

const userModule: Module<UserState, RootStateTypes> = {
  namespaced: true,
  state: {
    account: null,
    cookie: '',
    token: '',
    authPageList: [],
    authBtnList: []
  },
  mutations: {
    SET_ACCOUNT (state:UserState, account:user.UserInfo) {
      state.account = account
    },
    SET_TOKEN (state:UserState, token:string) {
      state.token = token
    },
    SET_COOKIE (state:UserState, cookie:string) {
      state.cookie = cookie
    },
    SET_AuthPageList(state:UserState, authPageList:Array<string>){
      state.authPageList = authPageList
    },
    SET_AuthBtnList(state:UserState, authBtnList:Array<string>){
      state.authBtnList = authBtnList
    }
  },
  actions: {
    setUser ({ commit }, data) {
      if (!data) {
        commit('SET_ACCOUNT', Session.get('account'))
        commit('SET_TOKEN', Session.get('token'))
        commit('SET_COOKIE', Session.get('cookie'))
        commit('SET_AuthPageList', Session.get('authPageList'))
        commit('SET_AuthBtnList', Session.get('authBtnList'))
      }
      if (data) {
        commit('SET_ACCOUNT', data.account)
        commit('SET_TOKEN', data.token)
        commit('SET_COOKIE', data.cookie)
        commit('SET_AuthPageList', data.authPageList)
        commit('SET_AuthBtnList', data.authBtnList)
      }
    },
    login ({ dispatch }, formdata) {
      return login(formdata).then(res => {
        const admin = true
        let auth:any = {}
        if(admin){
          auth = {
            authPageList: ['admin'],
            authBtnList: ['btn.add', 'btn.del', 'btn.edit', 'btn.link']
          }
        }else{
          auth = {
            authPageList: ['test'],
            authBtnList: ['btn.add', 'btn.link']
          }
        }
        dispatch('setUser', Object.assign({},auth,res.data))
      })
    }
  }
}
export default userModule
